//
//  StatusViewModel.swift
//  SHWeibo2.0
//
//  Created by 黄礼潮 on 16/2/28.
//  Copyright © 2016年 黄礼潮. All rights reserved.
//

import UIKit
import SDWebImage

//定义一个结构体
struct StatusCellViewLayout  {
    
    let margin:CGFloat = 12
    
    //头像的大小
    let iconSize:CGSize = CGSize(width: 36, height: 36)
    //图像的间距
    let pictureMargin:CGFloat = 2
    //每行的图片的数量
    let pictureImagesRow:CGFloat = 3
    //视图的宽度
    let pictureWidth:CGFloat
    //图像的宽高
    let pictureWH:CGFloat
    
    //toolbar的高度
    let toolbarHeight:CGFloat = 36
    
    //计算图片的尺寸
    let pictureViewSize: CGSize
    
    
    
    init(){
        
        pictureWidth = UIScreen.mainScreen().bounds.width - 2 * margin
        
        pictureWH = (pictureWidth - pictureMargin * (pictureImagesRow - 1)) / pictureImagesRow
        pictureViewSize = CGSize(width:pictureWH, height:pictureWH)
    }
    
    
}

//定义一个全局的StatusCellViewLayout

let CZCellViewLayout = StatusCellViewLayout()

class StatusViewModel:CustomStringConvertible {

    var status: Status
    //定义一个行高属性
    var rowHeight:CGFloat = 0
    //认证图标
    var usermenberView: UIImage?
    //会员图标
    var userVipView :UIImage?
    //来源
    var souceText: String?
    //时间
    var dateTime: NSDate?
    //定义一个缓存单张图片的变量
    var singleImage:[StatusPicture]?{
      //如果有转发微博配图，原创微博是没有图像的
       return status.retweeted_status?.pic_urls ?? status.pic_urls
    }
    //微博配图的大小
    var pictureSize = CGSizeZero
    //添加被转发微博的配图大小
    var reweteedPictureViewSize = CGSizeZero
    
    //被转发微博的文字
    var reweteedText:String?{
        if status.retweeted_status == nil{
          return nil
        }
        
        return "@" + (status.retweeted_status?.user?.screen_name ?? "") + ":" + (status.retweeted_status?.text ?? "")
    
    }
    //更新单张图片缓存对应的大小
    func updateSingleImageSize(){
    
        pictureSize = calcSinglePictureSize(status.pic_urls)
        
        reweteedPictureViewSize = calcSinglePictureSize(status.retweeted_status?.pic_urls)
    
    }
   
    
    //计算单张图像配图的大小
    private func calcSinglePictureSize(pic_urls:[StatusPicture]?) -> CGSize{
    
        if pic_urls?.count != 1 {
        
            return CGSizeZero
        }
        
        let urlString = pic_urls![0].thumbnail_pic
        
        //SDWebImage 如果有内存警告或者磁盘超限 会自动的清楚缓存
        guard let image = SDWebImageManager.sharedManager().imageCache.imageFromMemoryCacheForKey(urlString) else{
        
          return CGSizeZero
        }
        
        //得到单张图片 SDWebImage 3.7.4  会将从网络获取的图像 自动的按当前的设备的分辨率进行转换
        let scale = UIScreen.mainScreen().scale
        
        var size = CGSize(width: image.size.width * scale, height: image.size.height * scale)
        
        //处理图片过窄 或者过宽的问题
        
        let minWidth:CGFloat = 20
        let maxWidth:CGFloat = 300
        
        size.width = size.width < minWidth ? minWidth : size.width
        
        if size.width > maxWidth{
        
            size.width = maxWidth
            
            size.height = size.width * image.size.height / image.size.width
        
        }
    
       return size
    }
    //返回单张图片缓存的高度
    
     func caleRowHeight(){
        
          //判断当前有转发微博，有的话，就是原创 + 转发 + 配图 + margin 
          //没有转发微博  是原创 +  配图 +  margin 
        let layout = StatusCellViewLayout()
        let labelsize = CGSize(width: layout.pictureWidth, height: CGFloat(MAXFLOAT))
        
         //原创微博
        rowHeight += layout.iconSize.height + layout.margin * 2
        
        if let text = status.text {
        
            rowHeight += (text as NSString).boundingRectWithSize(labelsize, options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName: UIFont.systemFontOfSize(15)], context: nil).height
            
            rowHeight += layout.margin
        
        }
        
       //配图
        if status.pic_urls?.count > 0{
        
            rowHeight += pictureSize.height + layout.margin
        }
        
        //转发微博不一定有
        if status.retweeted_status != nil {
        
            if let text = reweteedText {
            
                rowHeight += (text as NSString).boundingRectWithSize(labelsize, options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName: UIFont.systemFontOfSize(14)], context: nil).height
                rowHeight += 2 * layout.margin
            }
            
            //如果有配图
            if status.retweeted_status?.pic_urls?.count > 0{
            
                rowHeight += reweteedPictureViewSize.height + layout.margin
            
            }
            
        
        }
        //加上toolbarHeight
        
        rowHeight += layout.toolbarHeight 
    
    }
    
    //构造函数的调用  使用微博模型实例化模型
    init(status: Status){
    
      self.status = status
      creatUserImage()
      creatUserData()
      
      pictureSize = calcPictureViewSize(status.pic_urls)
    //计算被转发微博配图的大小
      //  status.retweeted_status?.pic_urls
      reweteedPictureViewSize = calcPictureViewSize(status.retweeted_status?.pic_urls)
    }


}

extension StatusViewModel{
    
    //微博配图模型的大小
    private func calcPictureViewSize (pic_urls: [StatusPicture]?)-> CGSize {
        //获取图片的数量
        let count = pic_urls?.count ?? 0 //如果没有的话等于0  //这里不能写（Bug）status.pic_urls 被转发微博图片显示不出来，传递数据时出现了错误  改成参数pic_urls
        
        if count == 0{
         return CGSizeZero
        }
        let cellayout = StatusCellViewLayout()
        
        //根据图片的数量计算行数
        let row = CGFloat((count - 1) / Int(cellayout.pictureImagesRow) + 1)
        
        //根据行数计算返回图片的大小
        let height = row * cellayout.pictureViewSize.height + (row - 1) * cellayout.pictureMargin
    
      return CGSize(width:cellayout.pictureWidth, height:height)
    }
    
    //这个协议的方法  遵守CustomStringConvertible
    var description: String{ 
    
       return status.description
    }
    
    private func creatUserData(){
    
     if let source = status.source,
        startIndex = source.rangeOfString("\">")?.endIndex,
        endIndex = source.rangeOfString("</a>")?.startIndex {
        
            souceText = "来自" + source.substringWithRange(startIndex..<endIndex)
        
        }
    
     //创建日期
        
        dateTime = NSDate.cz_sinaDate(status.created_at)
    
    }

    private func creatUserImage(){
    
        if status.user?.mbrank > 0 && status.user?.mbrank < 7 {
         
            userVipView = UIImage(named:"common_icon_membership_level\(status.user?.mbrank)")
        }
        // 认证图标 -1：没有认证，0，认证用户，2,3,5: 企业认证，220: 达人
        switch status.user?.verified_type ?? -1{
            case 0: usermenberView = UIImage(named:"avatar_vip")
            case 2,3,5: usermenberView = UIImage(named:"avatar_enterprise_vip")
            case 220: usermenberView = UIImage(named:"avatar_grassroot")
        default: break
            
        }
    
    }

}